<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Material;
use App\Models\InventoryRecord;
use App\Models\Type;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * 显示仪表盘页面
     */
    public function index()
    {
        // 基础统计数据
        $totalMaterials = Material::count();
        $totalTypes = Type::count();
        $lowStockCount = Material::where('quantity', '<', 10)->count();
        $todayOperations = OperationLog::whereDate('created_at', Carbon::today())->count();

        // 库存趋势数据（最近30天）
        $stockTrend = $this->getStockTrend();

        // 类型分布数据
        $typeDistribution = $this->getTypeDistribution();

        // 最近操作记录
        $recentLogs = OperationLog::select('operation_logs.*', 'users.username')
            ->leftJoin('users', 'operation_logs.user_id', '=', 'users.id')
            ->latest('operation_logs.created_at')
            ->take(10)
            ->get();

        return view('dashboard', compact(
            'totalMaterials',
            'totalTypes',
            'lowStockCount',
            'todayOperations',
            'stockTrend',
            'typeDistribution',
            'recentLogs'
        ));
    }

    /**
     * 获取库存趋势数据
     */
    private function getStockTrend()
    {
        $days = 30;
        $labels = [];
        $data = [];

        for ($i = $days - 1; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i);
            $labels[] = $date->format('m-d');

            // 获取当天的库存总量
            $totalStock = Material::sum('quantity');
            $data[] = $totalStock;
        }

        return [
            'labels' => $labels,
            'data' => $data
        ];
    }

    /**
     * 获取类型分布数据
     */
    private function getTypeDistribution()
    {
        $types = Type::withCount('materials')->get();

        return [
            'labels' => $types->pluck('name'),
            'data' => $types->pluck('materials_count')
        ];
    }
}
